package com.wang.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.common.Result;
import com.wang.entity.Role;
import com.wang.service.RoleService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wy
 * @since 2022-02-10
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Resource
    private RoleService roleService;


    // 新增或者更新
    @PostMapping("/add")
    public Result save(@RequestBody Role role) {
        roleService.saveOrUpdate(role);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        roleService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        roleService.removeByIds(ids);
        return Result.success();
    }

//    @GetMapping
//    public Result findAll() {
//        return Result.success(roleService.list());
//    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(roleService.getById(id));
    }

    @GetMapping
    public IPage<Role> findPage(@RequestParam(defaultValue ="1" ) Integer pageNum,
                                @RequestParam(defaultValue ="10" ) Integer pageSize,
                                @RequestParam(defaultValue ="" ) String name
                                ){
        IPage<Role> page = new Page<Role>(pageNum, pageSize);
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        if(StrUtil.isNotEmpty(name)){
            queryWrapper.like(Role::getName,name);
        }

        return roleService.page(page,queryWrapper);
    }

    /**
     * 绑定角色和菜单的关系
     * @param roleId 角色id
     * @param menuIds 菜单id数组
     * @return
     */
//    @PostMapping("/roleMenu/{roleId}")
//    public Result roleMenu(@PathVariable Integer roleId, @RequestBody List<Integer> menuIds) {
//        roleService.setRoleMenu(roleId, menuIds);
//        return Result.success();
//    }
//
//    @GetMapping("/roleMenu/{roleId}")
//    public Result getRoleMenu(@PathVariable Integer roleId) {
//        return Result.success( roleService.getRoleMenu(roleId));
//    }
    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Role> list = roleService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "id");
        writer.addHeaderAlias("name", "用户名");
        writer.addHeaderAlias("description", "描述");


        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("角色信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<Role> roles = CollUtil.newArrayList();
        for (List<Object> row : list) {
            Role role = new Role();
            role.setName(row.get(0).toString());
            role.setDescription(row.get(1).toString());
            roles.add(role);
        }

        roleService.saveBatch(roles);
        return Result.success(true);
    }

//    @PostMapping("/roleMenu/{roleId}")
//    public Result roleMenu(@PathVariable Integer roleId,@RequestBody List<Integer> menuIds){
//        roleService.setRoleMenu(roleId,menuIds);
//        return Result.success();
//    }
    @PostMapping("/roleMenu/{roleId}")
    public Result roleMenu(@PathVariable Integer roleId, @RequestBody List<Integer> menuIds) {
        roleService.setRoleMenu(roleId, menuIds);
        return Result.success();
    }
    @GetMapping("/roleMenu/{roleId}")
    public Result getRoleMenu(@PathVariable Integer roleId) {
        return Result.success( roleService.getRoleMenu(roleId));
    }

}

